<template>
  <!-- 在模板顶部添加 -->
  <!-- <div style="position: fixed; top: 0; left: 0; z-index: 9999; background: white; padding: 10px;">
    <p>Posts 数据: {{ posts.length }} 条</p>
    <p>Filtered 数据: {{ filteredPosts.length }} 条</p>
    <p>第一条数据: {{ posts[0] }}</p>
  </div> -->

  <div class="blog">
    <header class="page-header">
      <div class="container">
        <h1>欢迎来到我的博客</h1>
        <p>分享技术、生活和思考</p>
        <router-link to="/write" class="write-btn">写博客</router-link>
      </div>
    </header>

    <main class="container">
      <div v-if="loading" class="loading-state">
        <p>正在加载文章...</p>
      </div>
      
      <div v-else-if="error" class="error-state">
        <p>加载失败，请刷新重试</p>
      </div>
      
      <div v-else>
        <div class="filter-controls">
          <div class="search-box">
            <input 
              type="text" 
              v-model="searchQuery" 
              placeholder="搜索文章标题或标签..."
              @input="filterPosts"
            >
            <i class="fas fa-search"></i>
          </div>
          
          <div class="sort-options">
            <select v-model="sortBy" @change="sortPosts">
              <option value="date-desc">最新发布</option>
              <option value="date-asc">最早发布</option>
              <option value="title-asc">标题 (A-Z)</option>
              <option value="title-desc">标题 (Z-A)</option>
            </select>
          </div>
        </div>
        
        <div v-if="filteredPosts.length === 0" class="empty-state">
          <p>暂无文章</p>
        </div>
        
        <div v-else class="blog-grid">
          <article 
            v-for="post in filteredPosts" 
            :key="post.id" 
            class="blog-card"
          >
            <div class="blog-image">
              <img :src="post.image || defaultImage " :alt="post.title">
              <div class="blog-badge">{{ post.tags[0] || '未分类' }}</div>
            </div>
            <div class="blog-content">
              <h3 class="blog-title">
                <router-link :to="`/post/${post.id}`">{{ post.title }}</router-link>
              </h3>
              <div class="blog-meta">
                <span class="blog-author">
                  <i class="fas fa-user"></i> {{ post.author_name || '匿名作者' }}
                </span>
                <span class="blog-date">
                  <i class="far fa-calendar-alt"></i> {{ formatDate(post.publish_time) }}
                </span>
                <span class="blog-views">
                  <i class="fas fa-eye"></i> {{ post.read_count || 0 }} 阅读
                </span>
              </div>
              <p class="blog-excerpt">{{ post.content.substring(0, 50) }}...</p>
              <div class="blog-actions">
                <router-link :to="`/post/${post.id}`" class="read-btn">
                  <i class="fas fa-book-open"></i> 阅读全文
                </router-link>
                <button 
                  v-if="userStore.isAuthor(post.author_id)" 
                  @click="deleteArticle(post.id)" 
                  class="delete-btn"
                >
                  <i class="fas fa-trash-alt"></i> 删除
                </button>
              </div>
            </div>
          </article>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { articleApi } from '@/api/api'
import { useUserStore } from '@/store/user'
import defaultImage from '@/assets/img/home-bg.jpg'

const posts = ref([])
const filteredPosts = ref([])
const searchQuery = ref('')
const sortBy = ref('date-desc')
const loading = ref(true)
const error = ref(false)
const userStore = useUserStore()

const formatDate = (dateStr) => {
  try {
    const date = new Date(dateStr)
    return isNaN(date) ? '未知日期' : date.toLocaleDateString()
  } catch {
    return '未知日期'
  }
}

const filterPosts = () => {
  if (!searchQuery.value) {
    filteredPosts.value = [...posts.value]
  } else {
    const query = searchQuery.value.toLowerCase()
    filteredPosts.value = posts.value.filter(post => 
      post.title.toLowerCase().includes(query) || 
      (post.tags && post.tags.some(tag => tag.toLowerCase().includes(query)))
    ) // 补全了这个右括号
  }
  sortPosts()
}

const sortPosts = () => {
  switch (sortBy.value) {
    case 'date-desc':
      filteredPosts.value.sort((a, b) => new Date(b.publish_time) - new Date(a.publish_time))
      break
    case 'date-asc':
      filteredPosts.value.sort((a, b) => new Date(a.publish_time) - new Date(b.publish_time))
      break
    case 'title-asc':
      filteredPosts.value.sort((a, b) => a.title.localeCompare(b.title))
      break
    case 'title-desc':
      filteredPosts.value.sort((a, b) => b.title.localeCompare(a.title))
      break
  }
}

const deleteArticle = async (postId) => {
  try {
    await articleApi.deleteArticle(postId)
    posts.value = posts.value.filter(post => post.id !== postId)
    filterPosts()
  } catch (error) {
    console.error('删除文章失败：', error)
    alert('删除文章失败，请重试')
  }
}

onMounted(async () => {
  try {
    const response = await articleApi.getArticleList()
    console.log('API响应:', response) // 调试日志
    
    if (Array.isArray(response)) {
      posts.value = response.map(post => ({
        ...post,
        // 确保所有必要字段都有默认值
        title: post.title || '无标题',
        content: post.content || '暂无内容',
        publish_time: post.publish_time || new Date().toISOString(),
        tags: post.tags || [],
        author_name: post.author_name || '匿名作者',
        read_count: post.read_count || 0
      }))
      console.log('处理后数据:', posts.value)

      filteredPosts.value = [...posts.value]
      console.log('处理又处理后数据:',  filteredPosts)
      sortPosts()
    } else {
      console.error('API返回数据格式错误:', response)
      error.value = true
    }
  } catch (err) {
    console.error('获取文章列表失败:', err)
    error.value = true
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>

/* 新增状态提示样式 */
.loading-state, .error-state, .empty-state {
  text-align: center;
  padding: 2rem;
  font-size: 1.2rem;
  color: #666;
}

.error-state {
  color: #dc3545;
}

.blog {
  padding-bottom: 4rem;
}

.page-header {
  background: linear-gradient(120deg, rgba(44, 62, 80, 0.9), rgba(52, 152, 219, 0.9)), url('@/assets/img/home-bg.jpg');
  color: white;
  padding: 6rem 0;
  text-align: center;
  margin-bottom: 3rem;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  background-blend-mode: overlay;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 0 0 30px 30px;
  position: relative;
}

.page-header .container {
  position: relative;
  z-index: 1;
}

.page-header h1 {
  font-size: 2.8rem;
  margin-bottom: 1rem;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.page-header p {
  font-size: 1.2rem;
  margin-bottom: 1.5rem;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.write-btn {
  display: inline-block;
  padding: 0.8rem 1.8rem;
  background-color: #28a745;
  color: white;
  border-radius: 30px;
  text-decoration: none;
  font-size: 1rem;
  font-weight: 500;
  transition: all 0.3s;
  box-shadow: 0 4px 10px rgba(40, 167, 69, 0.3);
}

.write-btn:hover {
  background-color: #218838;
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(40, 167, 69, 0.4);
}

.filter-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2rem;
  gap: 1rem;
  flex-wrap: wrap;
}

.search-box {
  position: relative;
  flex-grow: 1;
  max-width: 400px;
}

.search-box input {
  width: 100%;
  padding: 0.75rem 1rem 0.75rem 2.5rem;
  border: 1px solid #ddd;
  border-radius: 30px;
  font-size: 1rem;
  transition: all 0.3s;
}

.search-box input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}

.search-box i {
  position: absolute;
  left: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #7f8c8d;
}

.sort-options select {
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 30px;
  font-size: 1rem;
  background-color: white;
  cursor: pointer;
}

.blog-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 2rem;
}

.blog-card {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.blog-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
}

.blog-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.blog-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.blog-card:hover .blog-image img {
  transform: scale(1.05);
}

.blog-badge {
  position: absolute;
  top: 1rem;
  left: 1rem;
  background-color: rgba(52, 152, 219, 0.9);
  color: white;
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 500;
}

.blog-content {
  padding: 1.5rem;
}

.blog-title {
  margin: 0 0 0.5rem;
  font-size: 1.4rem;
}

.blog-title a {
  color: #2c3e50;
  text-decoration: none;
  transition: color 0.3s;
}

.blog-title a:hover {
  color: #3498db;
}

.blog-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1rem;
  font-size: 0.85rem;
  color: #7f8c8d;
}

.blog-meta i {
  margin-right: 0.3rem;
}

.blog-excerpt {
  /* 标准属性（部分浏览器支持） */
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  
  /* 现代浏览器支持 */
  display: -moz-box;
  -moz-line-clamp: 3;
  -moz-box-orient: vertical;
  
  /* 未来标准 */
  display: box;
  line-clamp: 3;
  box-orient: vertical;
}

.blog-actions {
  display: flex;
  gap: 0.75rem;
}

.read-btn, .delete-btn {
  flex: 1;
  padding: 0.5rem;
  border: none;
  border-radius: 5px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  text-decoration: none;
}

.read-btn {
  background-color: #3498db;
  color: white;
}

.read-btn:hover {
  background-color: #2980b9;
}

.delete-btn {
  background-color: #f8f9fa;
  color: #dc3545;
  border: 1px solid #dc3545 !important;
}

.delete-btn:hover {
  background-color: #f1f1f1;
}

@media (max-width: 768px) {
  .filter-controls {
    flex-direction: column;
  }
  
  .search-box {
    max-width: 100%;
  }
  
  .blog-grid {
    grid-template-columns: 1fr;
  }
  
  .page-header h1 {
    font-size: 2rem;
  }
  
  .page-header p {
    font-size: 1rem;
  }
}
</style>